package com.demo.accessibilitykeeper;

import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/9/23 18:06
 */
public class AccessibilityOperator {

    private static AccessibilityKeeperService accessibilityService;

    public static void setAccessibilityService(AccessibilityKeeperService service) {
        accessibilityService = service;
    }

    /**
     * 点击安装按钮（用于自动安装）
     */
    public static boolean clickInstallButton() {
        if (accessibilityService == null) {
            return false;
        }

        try {
            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode == null) {
                return false;
            }

            // 寻找安装按钮
            AccessibilityNodeInfo installButton = findInstallButton(rootNode);
            if (installButton != null && installButton.isEnabled()) {
                // 点击安装按钮
                boolean clicked = installButton.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                if (clicked) {
                    // 等待并处理后续的确认对话框
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        handleInstallConfirmation();
                    }, 1500);

                    return true;
                }
            }

            return false;

        } catch (Exception e) {
            Log.e("AccessibilityOperator", "Failed to click install button", e);
            return false;
        }
    }

    /**
     * 寻找安装按钮
     */
    private static AccessibilityNodeInfo findInstallButton(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }

        // 检查常见的安装按钮文本
        String[] installTexts = {"安装", "Install", "确认", "Confirm", "继续", "Continue", "下一步", "Next"};
        CharSequence nodeText = node.getText();
        CharSequence contentDesc = node.getContentDescription();

        if (nodeText != null) {
            String text = nodeText.toString().toLowerCase();
            for (String installText : installTexts) {
                if (text.contains(installText.toLowerCase()) && node.isClickable()) {
                    return node;
                }
            }
        }

        if (contentDesc != null) {
            String desc = contentDesc.toString().toLowerCase();
            for (String installText : installTexts) {
                if (desc.contains(installText.toLowerCase()) && node.isClickable()) {
                    return node;
                }
            }
        }

        // 递归查找子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            AccessibilityNodeInfo result = findInstallButton(child);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 处理安装确认对话框
     */
    private static void handleInstallConfirmation() {
        try {
            if (accessibilityService == null) {
                return;
            }

            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode == null) {
                return;
            }

            // 寻找确认按钮
            AccessibilityNodeInfo confirmButton = findConfirmButton(rootNode);
            if (confirmButton != null && confirmButton.isEnabled()) {
                confirmButton.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                // 继续处理可能的后续对话框
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    handleFinalInstallStep();
                }, 1500);
            }

        } catch (Exception e) {
            Log.e("AccessibilityOperator", "Failed to handle install confirmation", e);
        }
    }

    /**
     * 寻找确认按钮
     */
    private static AccessibilityNodeInfo findConfirmButton(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }

        String[] confirmTexts = {"确定", "OK", "确认", "Confirm", "允许", "Allow", "同意", "Agree"};
        CharSequence nodeText = node.getText();

        if (nodeText != null) {
            String text = nodeText.toString();
            for (String confirmText : confirmTexts) {
                if (text.equals(confirmText) && node.isClickable()) {
                    return node;
                }
            }
        }

        // 递归查找子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            AccessibilityNodeInfo result = findConfirmButton(child);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 处理最终安装步骤
     */
    private static void handleFinalInstallStep() {
        try {
            if (accessibilityService == null) {
                return;
            }

            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
            if (rootNode == null) {
                return;
            }

            // 检查是否安装完成
            AccessibilityNodeInfo doneButton = findDoneButton(rootNode);
            if (doneButton != null && doneButton.isEnabled()) {
                doneButton.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                // 安装完成，启动后续配置
//                new Handler(Looper.getMainLooper()).postDelayed(() -> {
//                    Context context = accessibilityService.getApplicationContext();
//                    Intent configIntent = new Intent(context, PostInstallConfigService.class);
//                    context.startService(configIntent);
//                }, 1000);


            }

        } catch (Exception e) {
            Log.e("AccessibilityOperator", "Failed to handle final install step", e);
        }
    }

    /**
     * 寻找完成按钮
     */
    private static AccessibilityNodeInfo findDoneButton(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }

        String[] doneTexts = {"完成", "Done", "打开", "Open", "启动", "Launch"};
        CharSequence nodeText = node.getText();

        if (nodeText != null) {
            String text = nodeText.toString();
            for (String doneText : doneTexts) {
                if (text.equals(doneText) && node.isClickable()) {
                    return node;
                }
            }
        }

        // 递归查找子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            AccessibilityNodeInfo result = findDoneButton(child);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 寻找应用图标（改进版本）
     */
    public static boolean moveAppToFolder(String packageName) {
        if (accessibilityService == null) {
            return false;
        }

        try {
            // 1. 寻找目标应用图标
            AccessibilityNodeInfo appIcon = findAppIcon(packageName);
            if (appIcon == null) {
                return false;
            }

            // 2. 长按应用图标
            performLongClick(appIcon);

            // 3. 等待编辑模式
            Thread.sleep(1000);

            // 4. 创建或寻找文件夹
            AccessibilityNodeInfo folder = findOrCreateFolder();

            // 5. 拖拽应用到文件夹
            if (folder != null) {
                dragToFolder(appIcon, folder);
                return true;
            }

            return false;

        } catch (Exception e) {
            Log.e("AccessibilityOperator", "Failed to move app", e);
            return false;
        }
    }

    /**
     * 寻找应用图标
     */
    static AccessibilityNodeInfo findAppIcon(String packageName) {
        AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
        if (rootNode == null) {
            return null;
        }

        return findNodeByPackage(rootNode, packageName);
    }

    /**
     * 根据包名查找节点
     */
    private static AccessibilityNodeInfo findNodeByPackage(AccessibilityNodeInfo node, String packageName) {
        if (node == null) {
            return null;
        }

        // 检查当前节点
        CharSequence contentDesc = node.getContentDescription();
        if (contentDesc != null && contentDesc.toString().contains(packageName)) {
            return node;
        }

        // 递归检查子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            AccessibilityNodeInfo result = findNodeByPackage(child, packageName);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 执行长按操作
     */
    private static void performLongClick(AccessibilityNodeInfo node) {
        if (node != null) {
            node.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
        }
    }

    /**
     * 寻找或创建文件夹
     */
    private static AccessibilityNodeInfo findOrCreateFolder() {
        AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();
        if (rootNode == null) {
            return null;
        }

        // 先尝试寻找现有文件夹
        AccessibilityNodeInfo existingFolder = findExistingFolder(rootNode);
        if (existingFolder != null) {
            return existingFolder;
        }

        // 如果没有现有文件夹，创建新的
        return createNewFolder();
    }

    /**
     * 寻找现有文件夹
     */
    private static AccessibilityNodeInfo findExistingFolder(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }

        // 检查是否是文件夹（通常文件夹会有特定的类名或描述）
        CharSequence className = node.getClassName();
        if (className != null && className.toString().contains("Folder")) {
            return node;
        }

        // 递归检查子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            AccessibilityNodeInfo result = findExistingFolder(child);
            if (result != null) {
                return result;
            }
        }

        return null;
    }

    /**
     * 创建新文件夹
     */
    private static AccessibilityNodeInfo createNewFolder() {
        try {
            AccessibilityNodeInfo rootNode = accessibilityService.getRootInActiveWindow();

            // 寻找两个相邻的应用图标
            List<AccessibilityNodeInfo> appIcons = findAllAppIcons(rootNode);

            if (appIcons.size() >= 2) {
                AccessibilityNodeInfo app1 = appIcons.get(0);
                AccessibilityNodeInfo app2 = appIcons.get(1);

                // 拖拽第一个应用到第二个应用上创建文件夹
                dragToPosition(app1, app2);

                // 等待文件夹创建
                Thread.sleep(1000);

                // 返回新创建的文件夹
                return findExistingFolder(accessibilityService.getRootInActiveWindow());
            }

        } catch (Exception e) {
            Log.e("AccessibilityOperator", "Failed to create folder", e);
        }

        return null;
    }

    /**
     * 寻找所有应用图标
     */
    private static List<AccessibilityNodeInfo> findAllAppIcons(AccessibilityNodeInfo node) {
        List<AccessibilityNodeInfo> icons = new ArrayList<>();

        if (node == null) {
            return icons;
        }

        // 检查当前节点是否是应用图标
        if (isAppIcon(node)) {
            icons.add(node);
        }

        // 递归检查子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            icons.addAll(findAllAppIcons(child));
        }

        return icons;
    }

    /**
     * 判断是否是应用图标
     */
    private static boolean isAppIcon(AccessibilityNodeInfo node) {
        CharSequence className = node.getClassName();
        return className != null &&
                (className.toString().contains("ImageView") ||
                        className.toString().contains("TextView")) &&
                node.isClickable();
    }

    /**
     * 拖拽到指定位置
     */
    private static void dragToPosition(AccessibilityNodeInfo source, AccessibilityNodeInfo target) {
        if (source == null || target == null) {
            return;
        }

        Rect sourceRect = new Rect();
        Rect targetRect = new Rect();

        source.getBoundsInScreen(sourceRect);
        target.getBoundsInScreen(targetRect);

        // 创建拖拽手势
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Path dragPath = new Path();
            dragPath.moveTo(sourceRect.centerX(), sourceRect.centerY());
            dragPath.lineTo(targetRect.centerX(), targetRect.centerY());

            GestureDescription.Builder builder = new GestureDescription.Builder();
            GestureDescription.StrokeDescription dragStroke =
                    new GestureDescription.StrokeDescription(dragPath, 0, 1000);
            builder.addStroke(dragStroke);

            accessibilityService.dispatchGesture(builder.build(), null, null);
        }
    }

    /**
     * 拖拽到文件夹
     */
    private static void dragToFolder(AccessibilityNodeInfo app, AccessibilityNodeInfo folder) {
        dragToPosition(app, folder);
    }

}
